package com.example.demo.util;

import com.example.demo.entity.UserPassword;
import org.apache.http.client.utils.DateUtils;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.util.StringUtils;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import javax.mail.*;
import javax.mail.internet.MimeMultipart;
import javax.mail.search.*;

public class DeleteEmail {

    public static void deleteInbox(String host, String user, String password,String path,String startDate) {
        try {
            //获取Session对象
            Properties properties = new Properties();
            properties.put("mail.store.protocol", "imap");
            properties.put("mail.imap.host", host);
            properties.put("mail.imap.port", "993");
            properties.put("mail.imap.ssl.enable", true);
            Session emailSession = Session.getDefaultInstance(properties);
            // emailSession.setDebug(true);

            //创建IMAP的Store对象并连接到IMAP服务
            Store store = emailSession.getStore("imap");

            store.connect(host, user, password);

            Folder defaultFolder = store.getDefaultFolder();
            Folder[] allFolder = defaultFolder.list();

            List<Folder> folderList = new ArrayList();
            Folder rmFolder = null;
            for (int i = 0; i < allFolder.length; i++) {
                if(allFolder[i].getFullName().indexOf("已删除")>-1){
                    rmFolder = allFolder[i];
                }else{
                    folderList.add(allFolder[i]);
                }
            }

            if(rmFolder!=null){
                folderList.add(rmFolder);
            }

            for (int i = 0; i < folderList.size(); i++) {

                //创建Folder对象并以读写模式打开
                Folder emailFolder = folderList.get(i);
                SearchTerm sentDateTerm = new SentDateTerm(ComparisonTerm.GE,new Date(DateUtils.parseDate(startDate,new String[]{"yyyy/MM/dd"}).getTime()));

                emailFolder.open(Folder.READ_WRITE);

                //查询Folder中的消息并打印
                Message[] messages = emailFolder.search(sentDateTerm);
                System.out.println("messages.length---" + messages.length);

                //获取关键字
                List<String> keyList = getKeyListStr(path);
                for (int j = 0; j < messages.length; j++) {
                    Message message = messages[j];
                    setMessageFlag(message,keyList);
                }

                //关闭folder时设置expunges为true表示移除标识为删除的消息
                emailFolder.close(true);
                store.close();
            }

        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 是否删除邮件（设置邮件删除标志）
     * @param message
     * @param keyList
     * @return
     */
    public static void setMessageFlag(Message message,List<String> keyList){
        try{
            System.out.println("---------------------------------");
            System.out.println("Subject: " + message.getSubject());
            System.out.println("From: " + message.getFrom()[0]);

            //获取邮件标题和正文
            String subject = message.getSubject();
            String messageText = "";
            if(message.isMimeType("Text/*")){
//                System.out.println("text格式正文: " + (String) message.getContent());
                messageText = (String) message.getContent();
            }else{
                MimeMultipart multPart = (MimeMultipart) message.getContent();
                for(int j = 0; j < multPart.getCount(); j++){
                    BodyPart body = multPart.getBodyPart(j);
                    if (body.isMimeType("text/html") || body.isMimeType("text/plain")) {
//                        System.out.println("正文: " + (String) body.getContent());
                        messageText = (String) body.getContent();
                    }
                }
            }

            //判断关键词是否命中邮件标题或正文
            for (String keyStr : keyList) {
                if(StringUtils.isEmpty(subject)){
                    subject = "";
                }
                if(StringUtils.isEmpty(messageText)){
                    messageText = "";
                }
                if (subject.indexOf(keyStr)>-1 || messageText.indexOf(keyStr) > -1) {
                    //调协消息标识为true表示消息消息
                    message.setFlag(Flags.Flag.DELETED, true);
                    break;
                }
            }
        } catch (NoSuchProviderException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static List<String> getKeyListStr(String path){
        List<String> keyStrList = new ArrayList<>();
        try {
            //读取关键字
            FileInputStream inputStream = new FileInputStream(path);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String str = null;

            while((str = bufferedReader.readLine()) != null)
            {
                keyStrList.add(str);
            }
            //close
            inputStream.close();
            bufferedReader.close();
        }catch (IOException io) {
            io.printStackTrace();
        }
        return keyStrList;

    }


    /**
     * 解析邮件
     */
    public static void parseMessage (MimeMultipart part) throws MessagingException, IOException {
        byte[] bytes = new byte[1024];
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();

        for (int i = 0; i < part.getCount(); i++) {
            BodyPart body = part.getBodyPart(i);
            if (body.isMimeType("text/html")) {
                System.out.println("html格式正文: " + (String) body.getContent());
            } else if (body.isMimeType("text/plain")) {
                System.out.println("纯文本格式正文: " + (String) body.getContent());
            } else if (body.isMimeType("multipart/*")) {
                MimeMultipart multipart = (MimeMultipart) body.getContent();
                parseMessage(multipart);
            } else { // 附件
//                InputStream inputStream = body.getDataHandler().getInputStream();
//                int len = 0;
//                while( (len = inputStream.read(bytes)) != -1 ){
//                    outStream.write(bytes, 0, len);
//                }
//                inputStream.close();
//                byte[] data = outStream.toByteArray();
//                String fileName = body.getFileName();
//                File tempFile = new File(FileUtils.getTempDirectoryPath() + File.separator + System.currentTimeMillis() + fileName );
//                FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
//                fileOutputStream.write(data);
//                fileOutputStream.close();
//                System.out.println("邮件附件本地路径: " + tempFile.getAbsolutePath());
            }
        }
    }

    public static List<UserPassword> getUserList(String userPath){
        List<UserPassword> userStrList = new ArrayList<>();
        try {
            //读取关键字
            FileInputStream inputStream = new FileInputStream(userPath);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String str = null;

            while((str = bufferedReader.readLine()) != null)
            {
                UserPassword userPassword = new UserPassword();
                String[] userArr = str.split(",");
                userPassword.setUser(userArr[0]);
                userPassword.setPassword(userArr[1]);

                userStrList.add(userPassword);
            }
            //close
            inputStream.close();
            bufferedReader.close();
        }catch (IOException io) {
            io.printStackTrace();
        }
        return userStrList;
    }

    /**
     * 批量删除用户邮箱信息
     * @param host
     * @param userStrList
     * @param keyPath
     * @param startDate
     */
    public static void deleteInboxForUserList(String host, List<UserPassword> userStrList,String keyPath,String startDate){
        userStrList.stream().forEach(user -> {
            deleteInbox(host, user.getUser(),user.getPassword(),keyPath,startDate);
        });
    }


    public static void main(String[] args) throws IOException {

        Scanner scanner = new Scanner(System.in);
        String host = "imap.qiye.aliyun.com";
        String keyPath = "d:\\key.txt";
        String userPath = "";
        String startDate="2020/06/01";
//        while (true) {
//            System.out.println("请imap服务器地址：");
//            host = scanner.nextLine();
//            if(StringUtils.isEmpty(host)){
//                System.out.println("输入不能为空！" );
//            }else{
//                break;
//            }
//        }
//        
//        while (true) {
//            System.out.println("请输入关键词存储路径：");
//            keyPath = scanner.nextLine();
//            if(StringUtils.isEmpty(keyPath)){
//                System.out.println("输入不能为空！" );
//            }else{
//                break;
//            }
//        }

        while (true) {
            System.out.println("请邮箱用户存储地址：");
            userPath = scanner.nextLine();
            if(StringUtils.isEmpty(userPath)){
                System.out.println("输入不能为空！" );
            }else{
                break;
            }
        }

//        while (true) {
//            System.out.println("请输入删除开始日期：");
//            startDate = scanner.nextLine();
//            if(StringUtils.isEmpty(startDate)){
//                System.out.println("输入不能为空！" );
//            }else{
//                break;
//            }
//        }

        deleteInboxForUserList(host, getUserList(userPath),keyPath,startDate);
    }

}
